package com.zh.note.leetcode.dp;

/**
 * 647. 回文子串
 */
public class LC_647_countSubstrings {
    //动态规划
    public int countSubstrings(String s) {
        char[] strs = s.toCharArray();
        int res = 0;
        //dp[i][j]：字符串s在[i, j]范围内最长的回文子序列的长度为dp[i][j]。
        boolean[][] dp = new boolean[strs.length + 1][strs.length + 1];
        for (int i = strs.length - 1; i >= 0; i--) {
            for (int j = i; j < strs.length; j++) {
                if (strs[i] == strs[j]) {
                    if (j - i <= 1) {
                        dp[i][j] = true;
                        res++;
                    } else if (dp[i + 1][j - 1] == true) {
                        dp[i][j] = true;
                        res++;
                    }
                }
            }
        }
        return res;
    }

    //双指针法
    public static int countSubstrings2(String s) {
        int res = 0;
        for (int i = 0; i < s.length(); i++) {
            res += extend(s, i, i, s.length()); //  以i为中心
            res += extend(s, i, i + 1, s.length()); //// 以i和i+1为中心
        }
        return res;

    }

    private static int extend(String s, int i, int j, int n) {
        int res = 0;
        while (i >= 0 && j < n && s.charAt(i) == s.charAt(j)) {
            i--;
            j++;
            res++;
        }
        return res;
    }

    public static void main(String[] args) {
        countSubstrings2("aba");

    }

}
